package com.yzxb.erpsystem.service.impl;

import com.yzxb.erpsystem.entity.Product;
import com.yzxb.erpsystem.mapper.ProductMapper;
import com.yzxb.erpsystem.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class ProductServiceImpl implements ProductService {
    
    @Autowired
    private ProductMapper productMapper;
    
    @Override
    @Transactional
    public Product createProduct(Product product) {
        // 非空校验
        if (product == null) {
            throw new IllegalArgumentException("商品信息不能为空");
        }
        
        if (product.getProductCode() == null || product.getProductCode().trim().isEmpty()) {
            throw new IllegalArgumentException("商品编码不能为空");
        }
        
        if (product.getProductName() == null || product.getProductName().trim().isEmpty()) {
            throw new IllegalArgumentException("商品名称不能为空");
        }
        
        if (product.getCategoryId() == null) {
            throw new IllegalArgumentException("分类ID不能为空");
        }
        
        if (product.getUnit() == null || product.getUnit().trim().isEmpty()) {
            throw new IllegalArgumentException("单位不能为空");
        }
        
        // 检查商品编码是否已存在
        if (productMapper.selectByProductCode(product.getProductCode()) != null) {
            throw new IllegalArgumentException("商品编码已存在");
        }
        
        // 设置价格默认值
        if (product.getCostPrice() == null) {
            product.setCostPrice(BigDecimal.ZERO);
        }
        
        if (product.getSalePrice() == null) {
            product.setSalePrice(BigDecimal.ZERO);
        }
        
        if (product.getStockQuantity() == null) {
            product.setStockQuantity(BigDecimal.ZERO);
        }
        
        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        product.setCreatedTime(now);
        product.setUpdatedTime(now);
        
        // 设置默认状态为启用
        if (product.getStatus() == null || product.getStatus().trim().isEmpty()) {
            product.setStatus("ACTIVE");
        }
        
        // 保存商品
        int rows = productMapper.insert(product);
        if (rows != 1) {
            throw new RuntimeException("创建商品失败");
        }
        
        return productMapper.selectById(product.getId());
    }
    
    @Override
    @Transactional
    public Product updateProduct(Long id, Product product) {
        // 参数校验
        if (id == null) {
            throw new IllegalArgumentException("商品ID不能为空");
        }
        
        if (product == null) {
            throw new IllegalArgumentException("商品信息不能为空");
        }
        
        // 查找现有商品
        Product existingProduct = productMapper.selectById(id);
        if (existingProduct == null) {
            throw new IllegalArgumentException("商品不存在");
        }
        
        // 更新商品信息
        product.setId(id);
        product.setCreatedTime(existingProduct.getCreatedTime());
        product.setUpdatedTime(LocalDateTime.now());
        
        // 检查商品编码是否重复（排除当前商品）
        Product productByCode = productMapper.selectByProductCode(product.getProductCode());
        if (productByCode != null && !productByCode.getId().equals(id)) {
            throw new IllegalArgumentException("商品编码已存在");
        }
        
        // 更新商品
        int rows = productMapper.update(product);
        if (rows != 1) {
            throw new RuntimeException("更新商品失败");
        }
        
        return productMapper.selectById(id);
    }
    
    @Override
    @Transactional
    public void deleteProduct(Long id) {
        // 参数校验
        if (id == null) {
            throw new IllegalArgumentException("商品ID不能为空");
        }
        
        // 查找商品
        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new IllegalArgumentException("商品不存在");
        }
        
        // 删除商品
        int rows = productMapper.deleteById(id);
        if (rows != 1) {
            throw new RuntimeException("删除商品失败");
        }
    }
    
    @Override
    public Optional<Product> getProductById(Long id) {
        if (id == null) {
            return Optional.empty();
        }
        
        Product product = productMapper.selectById(id);
        return Optional.ofNullable(product);
    }
    
    @Override
    public Optional<Product> getProductByProductCode(String productCode) {
        if (productCode == null || productCode.trim().isEmpty()) {
            return Optional.empty();
        }
        
        Product product = productMapper.selectByProductCode(productCode);
        return Optional.ofNullable(product);
    }
    
    @Override
    public List<Product> getAllProducts() {
        return productMapper.selectAll();
    }
    
    @Override
    public List<Product> getProductsByStatus(String status) {
        if (status == null || status.trim().isEmpty()) {
            return getAllProducts();
        }
        
        return productMapper.selectByStatus(status);
    }
    
    @Override
    public List<Product> getProductsByCategoryId(Long categoryId) {
        // 当前版本暂不支持按分类查询
        return getAllProducts();
    }
    
    @Override
    @Transactional
    public Product activateProduct(Long id) {
        Product product = getProductById(id)
                .orElseThrow(() -> new IllegalArgumentException("商品不存在"));
        
        product.setStatus("ACTIVE");
        product.setUpdatedTime(LocalDateTime.now());
        
        int rows = productMapper.update(product);
        if (rows != 1) {
            throw new RuntimeException("上架商品失败");
        }
        
        return product;
    }
    
    @Override
    @Transactional
    public Product deactivateProduct(Long id) {
        Product product = getProductById(id)
                .orElseThrow(() -> new IllegalArgumentException("商品不存在"));
        
        product.setStatus("INACTIVE");
        product.setUpdatedTime(LocalDateTime.now());
        
        int rows = productMapper.update(product);
        if (rows != 1) {
            throw new RuntimeException("下架商品失败");
        }
        
        return product;
    }
}